<template>
  <div :class="{'mobile-create': showMobilePage}" class="create-sign-up">
    <explanation :explanation="explanationObj" is-expand style="margin: 0;"/>
    <div :class="{'pb55':device!=='mobile'}" class="page-container">
      <AccountInfo ref="accountInfoRef" :params-obj="data" :platform-option="platformOption" :id="id" @selectAccount="selectAccount"/>
      <priceInfo v-model="data.additionalKey" :id="id" :platform-option="platformOption" :platform="data.platform" />
      <signUpInfo ref="signUpInfoRef" :params-obj="data"/>
      <AuditProcess
        ref="auditProcessRef"
        :loading="loading"
        v-model="auditInfo"
        :old-audit-info="oldAuditInfo"
        :default-aduitor-list="[{id:data.creatorId,userName:data.creator}]"
        :flow-structure="processDetail"
        :is-modify="Boolean(remodifyId)"
        :disable="Boolean(remodifyId)"
        :is-modify-form="Number(isModifyForm)"
        :current-process-index="Number(currentProcessIndex)"
        @submit="toSubmit"
        @getProcess="getProcess" />
      <fixed-pagination>
        <div class="center">
          <el-button v-if="remodifyId" size="small" type="primary" @click="openDrawer()">发起审批</el-button>
          <template v-else>
            <el-button v-if="showDraftBtn" :loading="draftLoading" class="empty-btn-style" size="small" type="info" @click="handleSave(1)">保存草稿</el-button>
            <el-button :loading="saveLoading" size="small" type="primary" @click="handleSave">保存</el-button>
          </template>
          <el-button class="cancel-btn-style" size="small" @click="handleCancel">取消</el-button>
        </div>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
import AccountInfo from '../components/accountInfo';
import signUpInfo from '../components/signUpInfo';
import priceInfo from '../components/createPriceInfo';
import AuditProcess from '@/components/Common/auditProcess';
import explanation from '@/components/Common/explanation';
import { addUp, upDetail, formSubmit, launchFilter } from '@/api/filter';
import ElMessage, { showModal } from '@/utils/message';
import { FIXED_PROCESS_TYPE } from '@/utils/const/process';
import { SUBMITTYPE } from '@/utils/const/cost';
import { createAuditStructure } from '@/utils/aduitor';
import { isContained } from '@/utils/tools';
import { platformList } from '@/api/select';
import { processManagementDetail } from '@/api/legal';
import processCreate from '@/mixins/processCreate';
import mobileCreate from '@/mixins/mobileCreate';
import { mapState } from 'vuex';
import math from '@/utils/math';

export default {
  components: { AccountInfo, signUpInfo, AuditProcess, explanation, priceInfo },
  mixins: [processCreate, mobileCreate],
  data() {
    return {
      SUBMITTYPE,
      data: {
        platform: '',
        link: '',
        accountName: '',
        accountId: '',
        gender: '',
        fans: '',
        agentObj: {
          id: '',
          userName: ''
        },
        departmentId: '',
        // category: [],
        shareRatio: '',
        shareRemark: '',
        additionalKey: {
          nextMonthReportPrice: {},
          nextMonthNotReportPrice: {},
          articlesPrice: {}
        }
      },
      id: 0,
      saveLoading: false,
      draftLoading: false,
      auditInfo: {
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      }, // 流程信息
      platformOption: [],
      processDetail: null,
      isEdit: false,
      remodifyId: null, // 修改，审批流程不能修改
      explanationObj: {
        content: '',
        styConfig: ''
      }, // 审批说明
      loading: false,
      oldAuditInfo: null // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
    };
  },
  computed: {
    ...mapState({
      'device': state => state.app.device,
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    showDraftBtn() {
      return this.isRescore || !this.data.id || (this.data.id && this.data.status === 0);
    },
    isRescore() {
      return !!this.$route.query.rescore;
    }
  },
  created() {
    const id = this.$route.query.id || this.$route.params.id;
    this.remodifyId = this.$route.query.remodifyId; // 修改
    if (id) {
      this.id = id;
      this.isEdit = true;
      this.getUpDetail();
      this.remodifyId && this.getExplanation();
    } else {
      this.isEdit = false;
    }
    this.getPlatformList();
  },
  methods: {
    // 获取下单平台的列表
    async getPlatformList() {
      try {
        const result = await platformList();
        this.platformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    getUpDetail() {
      upDetail(this.id).then(res => {
        if (res.code === 200) {
          this.data = res.data;
          if (!res.data.additionalKey) {
            this.data.additionalKey = {
              articlesPrice: {},
              nextMonthReportPrice: {},
              nextMonthNotReportPrice: {}
            };
          } else {
            if (!this.data.additionalKey.articlesPrice) {
              this.data.additionalKey.articlesPrice = {};
            }
            if (!this.data.additionalKey.nextMonthReportPrice) {
              this.data.additionalKey.nextMonthReportPrice = {};
            }
            if (!this.data.additionalKey.nextMonthNotReportPrice) {
              this.data.additionalKey.nextMonthNotReportPrice = {};
            }
          }
          if (res.data.gender !== 0) {
            this.data.gender = res.data.gender || '';
          }
          if (res.data.shareRatio) {
            res.data.talentSharingRatio = String(math.subtract(100, Number(res.data.shareRatio)));
          }
          /* if (this.data.category) {
            this.data.category = this.data.category.split(',').map(item => Number(item));
          } else {
            this.data.category = [];
          } */
          this.version = Number(res.data.version) || 0; // 当前详情版本，version存在mixins
          this.data.agentObj = { id: this.data.agentId, userName: this.data.agentName };
          if (res.data.auditInfo) {
            this.oldAuditInfo = Object.assign({}, res.data.auditInfo);
            this.auditInfo = JSON.parse(JSON.stringify(res.data.auditInfo));
            this.processDetail = JSON.parse(JSON.stringify(res.data.auditInfo));
          }
        }
      }).catch(err => {
        console.log(err);
      });
    },
    toSubmit(senders = []) {
      this.modifySenders = senders;// 存到mixins
      const params = JSON.parse(JSON.stringify(this.data));
      params.submitType = SUBMITTYPE.SUBMIT;
      params.isEditAudit = false;
      // params.category = params.category.join();
      if (this.remodifyId && this.isRefresh) {
        params.isEditAudit = true;// 修改时，流程被编辑或者更新
      }
      params.auditInfo = this.auditInfo;
      if (this.isModifyForm) { // 节点修改走编辑的逻辑
        params.id = this.id;
        this.handleModifyData(params);
        this.edit(params);
        return;
      }
      if (this.isEdit) {
        showModal('请确认是否发起审批').then(() => {
          this.handleModifyData(params);
          this.edit(params);
        });
      }
    },
    // 流程相关 start
    openDrawer() { // 流程弹窗
      const params = JSON.parse(JSON.stringify(this.data));
      params.accountName = params.accountName.trim();
      params.accountId = params.accountId.trim();
      // params.category = params.category.join();
      delete params.agentObj;
      this.isRescore && delete params.id;
      const promise = [];
      promise.push(this.$refs.accountInfoRef.validateForm());
      promise.push(this.$refs.signUpInfoRef.validateForm());
      Promise.all(promise).then(() => {
        if (!params.area) {
          ElMessage.warning('请选择达人所在城市');
          return;
        }
        this.getProcessDetail();
      }).catch(() => {});
    },
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    getProcessDetail(isRefresh) {
      const params = JSON.parse(JSON.stringify(this.data));
      params.accountName = params.accountName.trim();
      params.accountId = params.accountId.trim();
      // params.category = params.category.join();
      params.type = FIXED_PROCESS_TYPE.BLOGGER_FILTER; // 流程类型，达人初筛
      this.loading = true;
      formSubmit(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          const data = res.data;
          if (this.remodifyId && !isRefresh) {
            this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcessRef'].setShowRefresh(true);
          } else {
            this.processDetail = data;
            this.auditInfo.activeTime = data.activationTime;
            this.auditInfo.id = data.id;
            // 创建人回填
            const proposer = {
              id: this.data.creatorId,
              userName: this.data.creator
            };
            this.auditInfo.process = createAuditStructure(data.process, this.userInfo, proposer);
            this.auditInfo.senders = data.senderDiyUserList || [];
          }
          if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
            this.oldAuditInfo = Object.assign({}, data);
            this.oldAuditInfo.process.forEach(el => {
              this.oldAuditInfo.templateNodeId = el.id;
            });
            this.oldAuditInfo.activeTime = data.activationTime * 1000;
          }
          this.$refs['auditProcessRef'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      if (!isContained(nowProcessIds, oldProcessIds)) {
        return true;
      }
      return false;
    },
    edit(params) {
      this.loading = true;
      launchFilter(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$message.success(res.message);
          if (res.data.processId) {
            this.$router.push({
              name: 'filterDetail',
              query: { id: res.data.id, processId: res.data.processId }
            });
          } else {
            this.toBack();
          }
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcessRef'].setShowRefresh(true);
        }
        if (err.code === 505) { // 节点修改跳转详情
          this.nodeModifyJumpDetail({ routeName: 'filterDetail', params: {}, query: { id: this.id, processId: this.remodifyId }});
        }
        this.loading = false;
      });
    },
    getExplanation() { // 获取审批说明
      processManagementDetail({ id: 3527, type: FIXED_PROCESS_TYPE.BLOGGER_FILTER }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.explanationObj.content = data.explanation || '';
        this.explanationObj.styConfig = data.styConfig || '';
      }).catch(err => {
        console.log(err);
      });
    },
    selectAccount(val) {
      this.data.platform = val.platformType;
      this.data.link = val.resourceLink;
      this.data.accountName = val.resourceName;
      this.data.accountId = val.resourceId;
      this.data.gender = val.additionalKey.sex || '';
      this.data.fans = val.baseInfo.fansNum;
      this.data.agentId = val.additionalKey.contractBrokerId;
      this.data.agentName = val.additionalKey.contractBroker;
      this.data.agentObj = { id: val.additionalKey.contractBrokerId, userName: val.additionalKey.contractBroker };
      this.data.departmentId = val.additionalKey.signGroups;
      this.data.shareRatio = val.morePriceInfo.profitSharingRatio || '';
      this.data.shareRemark = val.morePriceInfo.profitSharingRemark;
      this.data.tag = val.baseInfo.tag || [];
      this.data.additionalKey = val.additionalKey || {};
      // 引用账号的additionalKey的相关数据可能为null，补上空对象防止报错
      if (!this.data.additionalKey.articlesPrice) {
        this.data.additionalKey.articlesPrice = {};
      }
      if (!this.data.additionalKey.nextMonthReportPrice) {
        this.data.additionalKey.nextMonthReportPrice = {};
      }
      if (!this.data.additionalKey.nextMonthNotReportPrice) {
        this.data.additionalKey.nextMonthNotReportPrice = {};
      }
    },
    handleSelectAccount() {
      this.selectAccountDialogVisible = true;
    },
    handleSave(isDraft = 0) {
      const params = JSON.parse(JSON.stringify(this.data));
      params.accountName = params.accountName.trim();
      params.accountId = params.accountId.trim();
      // params.category = params.category.join();
      delete params.agentObj;
      this.isRescore && delete params.id;
      if (isDraft === 1) {
        // 保存草稿不需要校验
        if (!this.data.platform || !this.data.accountId) {
          ElMessage.warning('请填写平台与账号ID');
          return;
        }
        this.handleSubmit(params, 1);
      } else {
        // 保存
        const promise = [];
        promise.push(this.$refs.accountInfoRef.validateForm());
        promise.push(this.$refs.signUpInfoRef.validateForm());
        Promise.all(promise).then(() => {
          if (!params.area) {
            ElMessage.warning('请选择达人所在城市');
            return;
          }
          this.handleSubmit(params, 2);
        }).catch(() => {});
      }
    },
    handleSubmit(params, submitType) {
      submitType === 1 ? this.draftLoading = true : this.saveLoading = true;
      params.submitType = submitType;
      params.createDeptId = this.userInfo.currentDeptIds ? this.userInfo.currentDeptIds[0] : '';
      addUp(params).then(res => {
        if (res.code === 200) {
          ElMessage.success('保存成功！');
          this.handleCancel();
        }
      }).finally(_ => {
        this.saveLoading = false;
        this.draftLoading = false;
      });
    },
    handleCancel() {
      this.$router.push({ name: 'filter' });
    }
  }
};
</script>

<style lang="scss" scoped>
.create-sign-up {
  margin: 16px;
  min-height: calc(100vh - 80px);
  background-color: #fff;
  &::v-deep {
    .el-form {
      .indentation-form-item {
        label {
          line-height: 1.2 !important;
        }
      }
    }
  }
}
.page-container {
  padding: 14px 24px 24px;
  &.pb55 {
    padding-bottom: 55px;
  }
}
.empty-btn-style {
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
  width: 80px;
  padding: 7px 0;
  text-align: center;
}
</style>
